package com.projectc.db.dao;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import javax.persistence.EntityManager;

import com.projectc.db.EMF;

public abstract class GenericDaoImpl<T> implements GenericDao<T> {

	private Class<T> type;

	@SuppressWarnings("unchecked")
	public GenericDaoImpl() {
		Type t = getClass().getGenericSuperclass();
		ParameterizedType pt = (ParameterizedType) t;
		type = (Class<T>) pt.getActualTypeArguments()[0];
	}

	@Override
	public T create(final T t) {
		EntityManager em = EMF.get().createEntityManager();
		try {
			em.persist(t);
			return t;
		} finally {
			em.close();
		}
	}

	@Override
	public void delete(final Object id) {
		EntityManager em = EMF.get().createEntityManager();
		try {
			em.remove(em.getReference(type, id));
		} finally {
			em.close();
		}
	}

	@Override
	public T find(final Object id) {
		EntityManager em = EMF.get().createEntityManager();
		try {
			return (T) em.find(type, id);
		} finally {
			em.close();
		}
	}

	@Override
	public T update(final T t) {
		EntityManager em = EMF.get().createEntityManager();
		try {
			return em.merge(t);
		} finally {
			em.close();
		}
	}
}